<?php

use Phphub\Core\CreatorListener;

class OpinionsController extends \BaseController implements CreatorListener
{
    public function __construct()
    {
        parent::__construct();
        $this->beforeFilter('auth');
    }

    public function authorOrAdminPermissioinRequire($author_id)
    {
        if (! Entrust::can('manage_opinions') && $author_id != Auth::id()) {
            throw new ManageOpinionsException("permission-required");
        }
    }

    public function store()
    {
        return App::make('Phphub\Creators\OpinionCreator')->create($this, Input::except('_token'));
    }

    public function vote($id)
    {
        $opinion = Opinion::find($id);
        App::make('Phphub\Vote\Voter')->opinionUpVote($opinion);
        return Redirect::route('reports.show', [$opinion->report_id, '#opinion'.$opinion->id]);
    }

    public function destroy($id)
    {
        $opinion = Opinion::findOrFail($id);
        $this->authorOrAdminPermissioinRequire($opinion->user_id);
        $opinion->delete();

        $opinion->report->decrement('opinion_count', 1);

        Flash::success(lang('Operation succeeded.'));

        return Redirect::route('reports.show', $opinion->report_id);
    }

    /**
     * ----------------------------------------
     * CreatorListener Delegate
     * ----------------------------------------
     */

    public function creatorFailed($errors)
    {
        Flash::error(lang('Operation failed.'));
        return Redirect::back();
    }

    public function creatorSucceed($opinion)
    {
        Flash::success(lang('Operation succeeded.'));
        return Redirect::route('reports.show', ['report_id' => $opinion->report_id]);
    }
}
